package nl.saxion.act.servlet;

import java.io.IOException;
import java.sql.Timestamp;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.derby.impl.sql.catalog.SYSPERMSRowFactory;

import nl.saxion.act.dao.AuctionDAO;
import nl.saxion.act.dao.BiddingDAO;
import nl.saxion.act.dao.CatagoryDAO;
import nl.saxion.act.dao.PersonDAO;
import nl.saxion.act.db.DatabaseManager;
import nl.saxion.act.wt.Auction;

/**
 * Servlet implementation class BidServlet
 */
public class BidServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private DatabaseManager dbMan;
	private ServletContext context;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BidServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public void init() throws ServletException {
    	context = this.getServletContext();
    	dbMan = (DatabaseManager) context.getAttribute("dbMan");   	
    }


	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		BiddingDAO bid = new BiddingDAO(dbMan);
		int bidderID = Integer.parseInt(request.getParameter("bidderID"));
		double price = Double.parseDouble(request.getParameter("price"));
		java.util.Date date= new java.util.Date();
		Timestamp bidTime = new Timestamp( date.getTime() );
		int auctionID = Integer.parseInt( request.getParameter("auctionID") );
		
		PersonDAO pd = new PersonDAO(dbMan);
		AuctionDAO auction1 = new AuctionDAO(dbMan);
		Auction auctionBid = auction1.getAuctionID(auctionID);
		
		RequestDispatcher view;
		if(auctionBid.getPrice() < price){
			auction1.updatePrice(auctionID, price);
			bid.insertBid(bidderID, price, bidTime, auctionID);
			//String bidderName = pd.getBidderNameByID(bidderID);
			auctionBid.setPrice(price);
			auctionBid.setAllBids(bid.getBidFromAuctions(auctionID));
			//auctionBid.setHighestBidderName(bidderName);
			auctionBid.getLastFewBidders();
			
			request.setAttribute("auction", auctionBid ) ;
			view = context.getRequestDispatcher("/fullInfo.jsp");
			
		} else{
			view = context.getRequestDispatcher("/tooLowBid.jsp");
		}
		
		CatagoryDAO catagory1 = new CatagoryDAO(dbMan);
		request.setAttribute("catagories", catagory1.getAllCatagory() );
		
		
		view.forward(request, response);
		
		
		
	}

}
